const { login } = require("../controller/user");
const { SuccessModel, ErrorModel } = require("../model/resModel");
// 设置cookie的有效时间
const setCookieEXpires = () => {
  const d = new Date();
  d.setTime(d.getTime() + 24 * 60 * 60 * 1000);
  return d.toGMTString();
};
// 登录
const loginCheck = (req) => {
  if (!req.session.username) {
      return Promise.resolve(
          new ErrorModel('尚未登录')
  )
  }
}
const handleUserRouter = (req, res,userid) => {
 
  // 登录
  if (req.method === "POST" && req.path === "/api/user/login") {
    const { username, password } = req.body;
    const result = login(username, password);
   
    return result.then((data) => { 
      if (data.username) {
        res.setHeader(
          "Set-Cookie",
          `userid=${userid};path=/;httpOnly;expires=${setCookieEXpires()}`
        );  
        req.session[userid].username=data.username
    

        // req.session.realname=data.realname
        return new SuccessModel("已经登录")
        }
        return new ErrorModel('meiyou')
    });
  }

  // if (req.method==='GET'&&req.path==="/api/user/text") {
  //   const { username, password } = req.query;
  //   // const result = login(username, password);
  //   if (req.cookie.username) {
  //     return Promise.resolve(new SuccessModel("已经登录"))
  //   }
  //   return Promise.resolve(new ErrorModel("登录失败"))
  // }

};
module.exports = handleUserRouter;
